<?php

namespace app\common\service;

use OSS\OssClient;
use OSS\Core\OssException;



/**
 * 阿里云对象存储服务
 *
 * Class AliOSS
 */
class AliOss
{
	private static $ossClient;
	private static $accessKeyId;
	private static $accessKeySecret;
	private static $endpoint;
	private static $bucket;

    /**
     * AliOSS constructor.
     * @param null $accessKeyId
     * @param null $accessKeySecret
     * @param null $endpoint
     * @param null $bucket
     * @throws OssException
     */
	public function __construct($accessKeyId = null, $accessKeySecret = null, $endpoint = null, $bucket = null)
	{
	 //    $config = Config('aliyun');

		// static::$accessKeyId = $accessKeyId ? $accessKeyId : $config['sms']['accessKeyId'];
		// static::$accessKeySecret = $accessKeySecret ? $accessKeySecret : $config['sms']['accessKeySecret'];
		// static::$endpoint = $endpoint ? $endpoint : $config['sms']['endpoint'];
		// static::$bucket = $bucket ? $bucket : $config['sms']['bucket'];


        static::$accessKeyId = $accessKeyId ? $accessKeyId : 'LTAI5t6Db6iU2M5b3S1anrQF';
        static::$accessKeySecret = $accessKeySecret ? $accessKeySecret : 'ySngRtoOr1x1qHAJELPfLjK0LBVH4F';
        static::$endpoint = $endpoint ? $endpoint : 'oss-cn-hangzhou.aliyuncs.com';
        static::$bucket = $bucket ? $bucket : 'fshitech';

		// 实例化oss对象
		static::$ossClient = new OssClient(static::$accessKeyId, static::$accessKeySecret, static::$endpoint);
		
	}

	/**
	 * 上传
	 * @param  string $uploadName 上传保存的文件名
	 * @param  string $filePath   本地文件路径
	 * @return array
	 */
	public function uploadCommon($uploadName, $filePath)
	{
		$result = static::$ossClient->uploadFile(static::$bucket, $uploadName, $filePath);

		if (!isset($result['info']) || empty($result['info'])) {
			return [
				'code' => -200,
				'msg' => '上传失败'
			];
		} else {
			return [
				'code'       => 200,
				'sourcePath' => $result['info']['url'],
				'smallPath'  => $result['info']['url'] . '?x-oss-process=style/compress',
			];
		}
	}

    /**
     * 上传文件流到oss
     *
     * @param $name
     * @param $stream
     * @return array|bool
     */
	public function uploadStream($name, $stream)
    {
        $result = static::$ossClient->putObject(static::$bucket, $name, $stream);

        if (!isset($result['info']) || empty($result['info'])) {
            return false;
        } else {
            return [
                'code'       => 0,
                'sourcePath' => $result['info']['url'],
                'smallPath'  => $result['info']['url'] . '?x-oss-process=style/small',
            ];
        }
    }

}